package com.adnaan.backend.service.impl;

import com.adnaan.backend.config.SiliconflowConfig;
import com.adnaan.backend.entity.ChatHistory;
import com.adnaan.backend.mapper.ChatHistoryMapper;
import com.adnaan.backend.service.AiService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;

@Slf4j
@Service
public class SiliconflowAiServiceImpl implements AiService {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private SiliconflowConfig siliconflowConfig;
    @Resource
    private ChatHistoryMapper chatHistoryMapper;

    @Override
    public void chat(String message, Consumer<String> onResponse, Consumer<Exception> onError, Runnable onComplete) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", siliconflowConfig.getModel());
            requestBody.put("messages", Collections.singletonList(
                    Map.of("role", "user", "content", "在中草药中" + message)
            ));
            requestBody.put("stream", true);
            requestBody.put("max_tokens", siliconflowConfig.getConfig().get("max_tokens"));

            // 创建URL连接
            URL url = new URL(siliconflowConfig.getUrl());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + siliconflowConfig.getKey());
            conn.setDoOutput(true);

            // 发送请求体
            String jsonBody = objectMapper.writeValueAsString(requestBody);
            conn.getOutputStream().write(jsonBody.getBytes(StandardCharsets.UTF_8));

            // 读取流式响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder currentMessage = new StringBuilder();
            boolean isFirstContent = true;

            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    String jsonData = line.substring(6);
                    if ("[DONE]".equals(jsonData)) {
                        onComplete.run();
                        break;
                    }
                    try {
                        Map<String, Object> responseMap = objectMapper.readValue(jsonData, Map.class);
                        List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
                        if (choices != null && !choices.isEmpty()) {
                            Map<String, Object> delta = (Map<String, Object>) choices.get(0).get("delta");
                            if (delta != null && delta.containsKey("content")) {
                                String content = (String) delta.get("content");
                                if (content != null) {
                                    log.info("回答：{}", content);
                                    // 处理第一个内容的换行符
                                    if (isFirstContent) {
                                        content = content.replaceAll("^\\n+", "");
                                        isFirstContent = false;
                                    }
                                    if (!content.isEmpty()) {
                                        currentMessage.append(content);
                                        onResponse.accept(content);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析SSE数据时出错: {}", e.getMessage());
                        onError.accept(e);
                    }
                }
            }

            reader.close();
            conn.disconnect();

        } catch (Exception e) {
            log.error("AI对话出错: {}", e.getMessage());
            onError.accept(e);
        }
    }

    @Override
    public List<Map<String, Object>> getHistory(Long userId) {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            List<ChatHistory> histories = chatHistoryMapper.selectList(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ChatHistory>()
                            .eq(ChatHistory::getUserId, userId)
                            .orderByDesc(ChatHistory::getCreateTime)
            );

            for (ChatHistory history : histories) {
                Map<String, Object> historyMap = new HashMap<>();
                historyMap.put("id", history.getId());
                historyMap.put("title", history.getTitle());
                historyMap.put("createTime", history.getCreateTime());

                // 解析消息内容
                List<Map<String, Object>> messages = objectMapper.readValue(
                        history.getMessages(),
                        new TypeReference<>() {
                        }
                );
                historyMap.put("messages", messages);

                result.add(historyMap);
            }

            return result;
        } catch (Exception e) {
            log.error("Error getting chat history: {}", e.getMessage());
            return new ArrayList<>();
        }
    }
} 